// pages/report/index.js
const App = getApp()
// let reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
let reg = /^1[0-9]{10}$/;
import moment from '../../utils/moment'
import Toast from '../../weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    api_root:'',
    status_true:0,
    show: false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } 
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      if (type === 'hour') {
        return `${value}时`;
      }
      if (type === 'minute') {
        return `${value}分`;
      }
      return value;
    },
    time: '',
    type: '',
    status: '',//新增编辑状态判断
    currentIndex2: '',
    content: "",
    ofent_list: ['正常维护', '下次继续', '未接电话'],
    fileList: [],
    project_name:'',
    report_form: {
      username: '',
      customer_id: '',
      project: '',
      agent_name: '',
      agent_mobile: '',
      inspect_time: '',
      company: '',
      carno: '',
      report_id: ''
    },
    summary_form: {
      customer_id: '',
      project: '',
      content: '',
      tags: '',
      remind_time: '',
      proof: '',
      record_id: '',
    },
    nopass_text:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let that = this
    let api_root = wx.getStorageSync('api_root')
      if(api_root){
        App.api_root = api_root;
      }
    that.setData({
      api_root:App.api_root ,
      nopass_text:options.nopass_text,
      status_true:options.status_true,
      type: options.type,
      ...this.data.report_form,
      ...this.data.summary_form,
      'report_form.customer_id': options.id,
      'report_form.report_id': options.reportid,
      'report_form.remind_id': options.remindid,
      'summary_form.customer_id': options.id,
      'summary_form.record_id': options.reportid,
      'summary_form.remind_id': options.remindid,
      'report_form.project':options.project_name,
      'summary_form.project': options.project_name,
      status: options.status,
      project_name:options.project_name
    })
    if (options.status == 1) {
      this.getInspectReport(options.reportid)
      this.getInspectSummary(options.reportid)
    }
  },
  onChange(e) {
    let { input } = e.currentTarget.dataset
    this.setData({
      report_form: {
        ...this.data.report_form,
        [input]: e.detail
      },
      summary_form: {
        ...this.data.summary_form,
        [input]: e.detail
      }
    })
  },
  //新增
  handleSave() {
    // console.log(this.data.report_form, this.data.summary_form)
    // return false;
    if (this.data.type == 1) {
      this.inspectReportUpdate()
    } else {
      this.inspectSummary()
    }
    
  },
  //编辑
  handleEdit() {
    if (this.data.type == 1) {
      this.editInspectReport()
    } else {
      this.editInspectSummary()
    }
    // console.log(this.data.report_form, this.data.summary_form)
  },
  onCancel() {
    console.log('1111')
    this.setData({
      show: false
    })
  },
  handleInput(e) {
    // let { type } = e.currentTarget.dataset
    this.setData({
      show: true
    })
  },
  onConfirm(event) {
    // console.log(event)
    let type = event.currentTarget.dataset.type
    let { value, index } = event.detail
    this.setData({
      show: false
    })
  },
  onInput(event) {
    this.setData({
      ...this.data.report_form,
      ...this.data.summary_form,
      'summary_form.remind_time': moment(event.detail).format("YYYY-MM-DD HH:mm:ss"),
      'report_form.inspect_time': moment(event.detail).format("YYYY-MM-DD HH:mm:ss"),
    });
  },
  //选择常用内容
  handleSelctOfen(e) {
    let { value, index } = e.currentTarget.dataset
    this.setData({
      currentIndex2: index,
      content: value
    })
  },

  //图片上传
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let _this = this
    let imgList = []
    for (let index = 0; index < file.length; index++) {
    wx.uploadFile({
      url: _this.data.api_root+'Customer/imageUpload', // 仅为示例，非真实的接口地址
      filePath: file[index].url,
      name: 'proof',
      success(res) {
        console.log(res)

        let arr_list = []
        // 上传完成需要更新 fileList
        const { fileList = [] } = _this.data;
        fileList.forEach(item => {
          arr_list.push(item)
        });
        fileList.push({ ...file[index], url: JSON.parse(res.data).data.url });
        arr_list.push({ ...file[index], url: JSON.parse(res.data).data.url });
        imgList = arr_list.map(item => {
          return item.url
        })
        imgList = imgList.join(',')
        // console.log(imgList)
        _this.setData({
          fileList,
          ..._this.data.summary_form,
          'summary_form.proof': imgList
        });
      },
    });
  }
  },
  //删除
  deleteImg(e) {
    const index = e.detail.index
    let imgList = []
    this.data.fileList.splice(index, 1)
    imgList = this.data.fileList.map(item => {
      return item.url
    })
    imgList = imgList.join(',')
    console.log(imgList)
    this.setData({
      fileList: this.data.fileList,
      ...this.data.summary_form,
      'summary_form.proof': imgList
    })
    console.log(e, this.data.fileList)
  },

  //带看报备详情
  getInspectReport(report_id) {
    let _this = this
    App._post_form('customer/getInspectReport', {
      report_id
    }, function (result) {
      _this.setData({
        report_form: result.data
      })
    });
  },

  //新增带看报备提交
  inspectReportUpdate() {
    let {project,agent_name,agent_mobile,company,carno} = this.data.report_form
    if(project == ''){
      Toast.fail('项目名不能为空')
      return false
    }
    // if(agent_name == ''){
    //   Toast.fail('姓名不能为空')
    //   return false
    // }
    // if(agent_mobile == ''){
    //   Toast.fail('手机不能为空')
    //   return false
    // }
    // if (!reg.test(agent_mobile)) {
    //   Toast.fail('手机号不符合要求');
    //   return false;
    // }
    // if(company == ''){
    //   Toast.fail('渠道不能为空')
    //   return false
    // }
    // if(carno == ''){
    //   Toast.fail('车牌不能为空')
    //   return false
    // }
    App._post('customer/inspectReportUpdate', this.data.report_form, function (result) {
      console.log(result);
      if (result.code === 0) {
        Toast({
          type: 'success',
          message: '提交成功',
          onClose: () => {
            wx.switchTab({
              url: '../index/index',
            })
          },
        });
      } else {
        Toast.fail(result.msg);
      }
    })
  },
  //修改带看报备提交
  editInspectReport() {
    let {project,agent_name,agent_mobile,company,carno} = this.data.report_form
    if(project == ''){
      Toast.fail('项目名不能为空')
      return false
    }
    // if(agent_name == ''){
    //   Toast.fail('姓名不能为空')
    //   return false
    // }
    // if(agent_mobile == ''){
    //   Toast.fail('手机不能为空')
    //   return false
    // }
    // if (!reg.test(agent_mobile)) {
    //   Toast.fail('手机号不符合要求');
    //   return false;
    // }
    // if(company == ''){
    //   Toast.fail('渠道不能为空')
    //   return false
    // }
    // if(carno == ''){
    //   Toast.fail('车牌不能为空')
    //   return false
    // }
    App._post('customer/editInspectReport', this.data.report_form, function (result) {
      if (result.code === 0) {
        Toast({
          type: 'success',
          message: '修改成功',
          onClose: () => {
            wx.switchTab({
              url: '../index/index',
            })
          },
        });
      } else {
        Toast.fail(result.msg);
      }
    })
  },

  //带看总结详情
  getInspectSummary(record_id) {
    let _this = this
    console.log(record_id);
    App._post_form('customer/getInspectSummary', {
      record_id
    }, function (result) {
      console.log(result);
      let arr_list = []
      let arr = result.data.proof.split(',')

      arr.forEach(item => {
        if (item.indexOf('https') == -1) {
          arr_list.push({
            url: _this.data.api_root+`${item}`
          })
        } else {
          arr_list.push({
            url: item
          })
        }
      });
      _this.setData({
        summary_form: result.data,
        fileList: arr_list
      })
    });
  },
  //新增带看总结
  inspectSummary() {
    let {project,content} = this.data.summary_form
    if(project == ''){
      Toast.fail('项目名不能为空')
      return false
    }
    if(content == ''){
      Toast.fail('跟进内容不能为空')
      return false
    }
    App._post('customer/inspectSummary', this.data.summary_form, function (result) {
      if (result.code === 0) {
        Toast({
          type: 'success',
          message: '提交成功',
          onClose: () => {
            wx.switchTab({
              // url: '../index/index?val=2',
              url: '../index/index',
            })
          },
        });
      } else {
        Toast.fail(result.msg);
      }
    })

  },
  //修改带看总结
  editInspectSummary() {
    let _this = this
    _this.data.summary_form.proof = _this.data.summary_form.proof.split(',')
    _this.data.summary_form.proof = _this.data.summary_form.proof.map(item => {
      return item.replace(_this.data.api_root, '')
    });
    _this.data.summary_form.proof = _this.data.summary_form.proof.join(',')
    _this.setData({
      ..._this.data.summary_form,
      'summary_form.proof': _this.data.summary_form.proof
    })
    // console.log(_this.data.summary_form);
    // return false;
    App._post_form('customer/editInspectSummary', _this.data.summary_form, function (result) {
      if (result.code === 0) {
        Toast({
          type: 'success',
          message: '提交成功',
          onClose: () => {
            wx.switchTab({
              url: '../index/index',
            })
          },
        });
      } else {
        Toast.fail(result.msg);
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})